package com.rgst.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.rgst.validator.em.IsIdNo;

/**
 * Created by tancw on 2019/12/1.
 */
public class IsIdNoValidator implements ConstraintValidator<IsIdNo, String> {

    private boolean notEmpty = false;

    final static String  regex_idno = "\\d{15}(\\d{2}[0-9xX])?";

    @Override
    public void initialize(IsIdNo constraintAnnotation) {
        notEmpty = constraintAnnotation.notEmpty();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (notEmpty) {
            if (value == null) return true;
            if (value.trim() == "") return true;
            return isIdno(value);
        }
        return false;
    }

    private boolean isIdno(String value) {
        return value.matches(regex_idno);
    }
}
